package com.gujiangbo.reference;

import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.util.concurrent.TimeUnit;

/**
 * @Author: gujiangbo.co
 * @Contact: 646832012@qq.com
 * @Date: 2022/3/12 09:36
 * @Version: 1.0
 * @Description: Reference Queue 引用队列。 被回收的引用在gc后都要被放入到引用队列之中。
 */
public class ReferenceQueueDemo {


    public static void main(String[] args) throws InterruptedException {
        Object flag = new Object();
        ReferenceQueue<Object> stringReferenceQueue = new ReferenceQueue<>();
        PhantomReference<Object> reference = new PhantomReference<>(flag, stringReferenceQueue);
        System.out.println(flag);
        System.out.println(stringReferenceQueue.poll());
        System.out.println(reference.get());

        System.out.println("===================");
        flag = null;
        System.gc();
        TimeUnit.SECONDS.sleep(1);
        System.out.println(flag);
        System.out.println(stringReferenceQueue.poll());// gc后将虚引用放入到引用队列之中
        System.out.println(reference.get());

    }


}
